<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-message"></i> 公共镜像</el-breadcrumb-item>
            </el-breadcrumb>

            <!--<div style="display:inline;float: right">-->
                <!--<el-button type="primary" icon="delete" class="handle-del mr10" >+ Pull Images</el-button>-->
            <!--</div>-->

            <el-tooltip class="item" effect="dark" content="从docker hub上拉取镜像" placement="top-start" style="display:inline;float: right">
                <!--<el-button>下边</el-button>-->
                <el-button type="primary" icon="delete" class="handle-del mr10" @click="table_pull()">+ Pull Images</el-button>
            </el-tooltip>

        </div>
        <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%">
            <el-table-column
                label="镜像名"
                width="200">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            <el-tag size="medium">{{ scope.row.fullName }}</el-tag>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="介绍"
                width="180">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.description }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="使用说明"
                width="280">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.instructions }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="镜像大小"
                width="180">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.size }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="来源"
                width="180">
                <template slot-scope="scope">
                    <el-popover >
                        <div slot="reference" class="name-wrapper">
                            {{ scope.row.authorName }}
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="getDetails(scope.$index, scope.row)">详情</el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="exportImage(scope.$index, scope.row)">导出</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页效果-->
        <div class="fenYe">
            <div class="block">
                <el-pagination
                    @current-change="handleCurrentChange"
                    :page-size="5"
                    layout="prev, pager, next, jumper"
                    :total="listTotal">
                </el-pagination>
            </div>
        </div>

        <!--详情提示框-->
        <el-dialog
            title="详细信息"
            :visible.sync="dialogVisible"
            width="50%"
            :before-close="handleClose">

            <div id="editor" class="json-editor"></div>
            <pre id="json"></pre>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                 <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="拉取镜像"
            :visible.sync="dialogVisible1"
            width="50%"
            :before-close="handleClose">

            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="镜像名称" prop="fullName">
                    <el-input v-model="form.fullName"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitToPullImage">立即拉取</el-button>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible1 = false">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import '../../../static/js/jsoneditor'
    export default {
        name: "Table-images",
        data() {
            return {
                tableData:[],
                dialogVisible:false,
                listTotal:0,
                currentPage:1,
                loading: true,
                dialogVisible1:false,
                form:{
                  fullName:'',
                },
                userId:'',


            }
        },
        methods: {
            getDetails(index, row) {
                console.log(index, row.imageId);
                this.getImageDetails(row.imageId);

            },
            exportImage(index, row) {
                console.log(index, row);
                this.downImage(row.fullName);
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            table_pull() {
                this.dialogVisible1=true;


            },

            getAllImagesHasOpen() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/getAllImagesHasOpen";
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取公共镜像列表");
                         this.tableData=res.data.data;
                    } else {
                        this.$message.error("获取公共镜像列表失败1");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取公共镜像列表失败2");
                })

            },
            getImageDetails(imageId) {
                this.dialogVisible=true;

                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/getDetailAboutImage"+"?imageId="+imageId;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取镜像详细信息");

                        let json = res.data.data;
                        $('#editor').jsonEditor(json, {
                            change: function () {
                                $('#json').html(JSON.stringify(json));
                            }
                        });

                    } else {
                        this.$message.error("获取镜像详细信息失败1");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取镜像详细信息失败2");
                })

            },
            downImage(fullName) {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/downImage"+"?fullName="+fullName;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        alert("点击确认，开始下载；\n下载比较慢，请耐心等候！");
                        window.open(res.data.data);

                    } else {
                        this.$message.error("获取image的下载地址失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取image的下载地址失败");
                })
            },
            getImagesHasOpenTotal() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/getTotalOfImagesHasOpen";
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                       this.$message.success("获取image的total成功")
                        this.listTotal = res.data.data;

                    } else {
                        this.$message.error("获取image的total失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取image的total失败");
                })
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/getAllImagesHasOpenWithPage"+"?pageIndex="+this.currentPage;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取公共镜像列表")
                        this.tableData=res.data.data;
                        for(var i=0;i<this.tableData.length;i++) {
                            // if (this.tableData[i].size<1024)
                            this.tableData[i].size=this.renderSize(this.tableData[i].size);
                        }

                    } else {
                        this.$message.error("获取公共镜像列表失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取公共镜像列表失败");
                })
            },
            getFirstImages() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/getAllImagesHasOpenWithPage"+"?pageIndex=1";
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success("成功获取公共镜像列表");
                        this.tableData=res.data.data;
                        this.loading=false;
                        for(var i=0;i<this.tableData.length;i++) {
                            // if (this.tableData[i].size<1024)
                            this.tableData[i].size=this.renderSize(this.tableData[i].size);
                        }

                    } else {
                        this.$message.error("获取公共镜像列表失败");
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error("获取公共镜像列表失败");
                })
            },
            //  格式化文件大小
            renderSize(value) {
                if (null == value || value == '') {
                    return "0 Bytes";
                }
                var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
                var index = 0,
                    srcsize = parseFloat(value);
                index = Math.floor(Math.log(srcsize) / Math.log(1024));
                var size = srcsize / Math.pow(1024, index);
                //  保留的小数位数
                size = size.toFixed(2);
                return size + unitArr[index];
            },

            //拉取镜像
            submitToPullImage() {
                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                var url = "/api/docker/customer/imagePull"+"?fullName="+this.form.fullName;
                this.$axios.get(url,config).then(res=>{
                    console.log(res);
                    if(res.data.code===1) {
                        this.$message.success(res.data.data);
                    } else {
                        this.$message.error(res.data.msg);
                    }
                }).catch(reason => {
                    console.log(reason);
                    this.$message.error(reason);
                })
            },

            //连接websocket
            conectWebSocket(){

                var token='Bearer '+sessionStorage.getItem("Token");
                let config = {
                    headers: {
                        'Authorization':token,
                    }
                };
                console.log(token);
                var url = "/api/user/getPersonalInfo";
                console.log(url);
                this.$axios.get(url,config).then(res=> {
                    console.log(res);
                    if(res.data.code===1) {
                        this.userId = res.data.data.id;
                        this.websock = new WebSocket("ws://localhost:8082"+"/ws/"+this.userId);

                        this.websock.onopen = this.websocketonopen;

                        // this.websock.onerror = this.websocketonerror;

                        this.websock.onmessage = this.websocketonmessage;

                        this.websock.onclose = this.websocketclose;

                    } else {
                        this.$message.error(res.data.msg);
                    }
                }).catch( res => {
                    console.log(res);
                })
            },

            websocketonopen:function() {
                console.log("WebSocket连接成功");
            },

            websocketonerror:function(e) { //错误
                console.log("WebSocket连接发生错误");
            },

            websocketonmessage:function(e){ //数据接收
                // this.$message.warning(e.data);
                this.$notify({
                    title: '消息推送',
                    message: e.data,
                    position: 'top-left'
                });
                // console.log(e.data);
            },

            websocketsend:function(agentData){//数据发送
                this.websock.send(agentData);
            },

            websocketclose:function(e){ //关闭
                console.log("connection closed (" + e.code + ")");
            },

        },
        created() {
            // this.getAllImagesHasOpen();
             this.getFirstImages();
            // this.getAllImagesHasOpen();
            this.getImagesHasOpenTotal();

            this.conectWebSocket();

        }
    }
</script>

<style scoped>

</style>
